import LimitPromise from "./LimitPromise.ts";

const useSessionStore = true
const useIframeDic = true


let getDictionaryInfoCache = {}
if (useSessionStore) {
  try {
    let str = sessionStorage.getItem("getDictionaryInfoCache") || '{}'
    getDictionaryInfoCache = JSON.parse(str);
  } catch (e) {
  }
}
let getDictionaryInfoLimitProm = {}

let dictCacheLimit = {
  call(key, call) {
    const dictionaryInfoCacheElement = getDictionaryInfoCache[key];
    if (dictionaryInfoCacheElement) {
      const res1 = dictionaryInfoCacheElement.res;
      if (dictionaryInfoCacheElement.status === 'err') {
        delete getDictionaryInfoCache[key]
        return Promise.reject(res1)
      }
      if (getDictionaryInfoLimitProm[key] && getDictionaryInfoLimitProm[key]._count === 0) {
        delete getDictionaryInfoLimitProm[key]
      }
      return Promise.resolve(dictCacheLimit.deepClone(res1))
    }
    if (getDictionaryInfoLimitProm[key]) {
      return getDictionaryInfoLimitProm[key].call(() => {
        return this.call(key, call)
      })
    }
    getDictionaryInfoLimitProm[key] = new LimitPromise(1)
    return getDictionaryInfoLimitProm[key].call(() => {
      return call().then(res => {
        getDictionaryInfoCache[key] = {
          status: 'finished',
          res: res
        }
        return res
      }).catch(err => {
        getDictionaryInfoCache[key] = {
          status: 'err',
          res: err
        }
        return Promise.reject(err)
      }).finally(() => {
        if (useSessionStore) {
          sessionStorage.setItem("getDictionaryInfoCache", JSON.stringify(getDictionaryInfoCache))
        }
      })
    })
  },
  getLocalWindowTop() {
    let result = window
    while (true) {
      if (result === result.parent) {
        return result
      }
      try {
        let o = result.parent.location.origin
        result = result.parent
      } catch (e) {
        return result
      }
    }
  },
  deepClone(obj) {
    let newObj = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === "object") {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = (obj && typeof obj[key] === 'object') ? dictCacheLimit.deepClone(obj[key]) : obj[key];
        }
      }
    }
    return newObj;
  }
}

if (useIframeDic) {
  // 配置多iframe全局缓存
  if (dictCacheLimit.getLocalWindowTop().__gloabel__cache__dictCacheLimit) {
    dictCacheLimit = dictCacheLimit.getLocalWindowTop().__gloabel__cache__dictCacheLimit
  } else {
    dictCacheLimit.getLocalWindowTop().__gloabel__cache__dictCacheLimit = dictCacheLimit
  }
}

export default dictCacheLimit
